<template>
	<el-form-item ref="formItem" :prop="prop" :rules="rules">
		<template #label>
			<WtmLabelTooltip :label="label" :tooltip="tooltip" />
		</template>
		<el-select
			v-model="modelValue"
			:clearable="clearable"
			:filterable="filterable"
			:disabled="disabled"
			:placeholder="placeholder"
			:loading="loading"
			@change="handleOrgChange"
			@clear="handleOrgClear"
			class="width100"
		>
			<el-option v-for="item in options" :key="item.Value" :value="item.Value" :label="item.Text" />
		</el-select>
	</el-form-item>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch, nextTick } from 'vue';
import other from '/@/utils/other';

// 定义组件名称
defineOptions({
	name: 'WtmOrgSelector',
});

// 定义 Props
interface Props {
	/** 组织v-model绑定值 */
	modelValue?: string | number | null;
	/** 组织数据，如果不传则自动加载 */
	options?: any[];
	/** 组织API接口地址 */
	apiUrl?: string;
	/** 是否可清空 */
	clearable?: boolean;
	/** 是否可搜索 */
	filterable?: boolean;
	/** 是否禁用 */
	disabled?: boolean;
	/** 组织占位符 */
	placeholder?: string;
	/** 组织标签 */
	label?: string;
	/** 组织表单属性名 */
	prop?: string;
	/** 组织验证规则 */
	rules?: any[];
	/** 组织提示 */
	tooltip?: string;
	/** 是否启用认证 */
	auth?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
	modelValue: null,
	options: undefined,
	apiUrl: '/api/common/GetUserCompanies',
	clearable: true,
	filterable: true,
	disabled: false,
	placeholder: '请选择公司',
	label: '公司',
	prop: 'Entity.OrgId',
	rules: () => [],
	tooltip: '公司',
	auth: false,
});

// 定义 Emits
const emit = defineEmits<{
	'update:modelValue': [value: string | number | null];
	change: [value: string | number | null];
	clear: [];
}>();

// 响应式数据
const loading = ref(false);
const internalOptions = ref<any[]>([]);
const lastLoadTime = ref(0); // 记录上次加载时间，防止频繁请求

// 计算属性
const modelValue = computed({
	get: () => props.modelValue,
	set: (value) => emit('update:modelValue', value),
});

const options = computed(() => {
	return props.options || internalOptions.value;
});

// 下拉选择器配置 - 使用简单的选项列表

const buildApiUrl = (baseUrl: string, params: Record<string, any>): string => {
	const queryParams = new URLSearchParams();
	Object.entries(params).forEach(([key, value]) => {
		if (value !== undefined && value !== null && value !== '') {
			queryParams.append(key, String(value));
		}
	});
	const separator = baseUrl.includes('?') ? '&' : '?';
	return `${baseUrl}${separator}${queryParams.toString()}`;
};
// 方法
const loadOptions = async () => {
	if (props.options) {
		return;
	}

	// 防止重复请求：检查加载状态和时间间隔
	const now = Date.now();
	const timeSinceLastLoad = now - lastLoadTime.value;
	const minInterval = 1000; // 最小间隔1秒

	if (loading.value) {
		return;
	}

	if (timeSinceLastLoad < minInterval) {
		return;
	}

	try {
		loading.value = true;
		lastLoadTime.value = now;
		const apiUrl = buildApiUrl(props.apiUrl, { auth: props.auth });
		const result = await other.getSelectList(apiUrl, [], false);
		internalOptions.value = result;
	} catch (error) {
		console.error('组织选择器加载失败:', error);
		internalOptions.value = [];
	} finally {
		loading.value = false;
	}
};

const handleOrgChange = (value: string | number | null) => {
	emit('change', value);
};

const handleOrgClear = () => {
	emit('clear');
};

// 监听 options 变化
watch(
	() => props.options,
	(newOptions) => {
		if (newOptions) {
			internalOptions.value = newOptions;
		}
	},
	{ immediate: true }
);

// 监听 apiUrl 变化
watch(
	() => props.apiUrl,
	() => {
		if (!props.options) {
			loadOptions();
		}
	}
);

// 监听 auth 变化
watch(
	() => props.auth,
	() => {
		if (!props.options) {
			loadOptions();
		}
	}
);

// 监听 modelValue 变化，确保选项加载完成后能正确显示
watch(
	() => props.modelValue,
	(newValue, oldValue) => {
		// 只在有新值且值真正发生变化时才处理
		if (newValue && newValue !== oldValue && !props.options && !loading.value) {
			const hasOptions = options.value.length > 0;

			if (!hasOptions) {
				// 没有选项时，立即加载
				loadOptions();
			}
		}
	},
	{ immediate: false }
);

// 监听内部选项列表变化，确保数据回显正确
watch(
	() => internalOptions.value,
	() => {
		// 选项列表更新后的处理逻辑（已移除调试日志）
	},
	{ immediate: false, deep: true }
);

// 生命周期
onMounted(async () => {
	// 如果没有外部提供选项，则自动加载
	if (!props.options) {
		await loadOptions();
	}
});
</script>

<style scoped>
.width100 {
	width: 100%;
}

.mb20 {
	margin-bottom: 20px;
}
</style>
